# uncompyle6 version 3.2.3
# Python bytecode 3.6 (3379)
# Decompiled from: Python 3.6.8 |Anaconda custom (64-bit)| (default, Feb 21 2019, 18:30:04) [MSC v.1916 64 bit (AMD64)]
# Embedded file name: helpers\db_updates.py
__author__ = "Attila Gerendi (Sanyi)"
import logging
from sqlalchemy import select as sql_select
from sqlalchemy import text as sql
from db import Connection
from db.tables.targets import TargetRow, TargetsTable
from helpers.address import get_canonical_address
from helpers.hashing import md5

_logger = logging.getLogger("db_updates")


def update_targets_address_canonical_form(shard):
    with Connection(shard) as (db):
        r = sql_select((sql("acx_get_db_version()"),))
        if db.execute(r).scalar() != 14:
            _logger.debug("abort updating since db version is not 14")
            return
        cursor = 0
        limit = 25
        while True:
            _logger.debug("updating canonical address %s:%s", cursor, limit)
            q = (
                sql_select((TargetRow.address, TargetRow.target_id, TargetRow.owner_id))
                .limit(limit)
                .offset(cursor)
                .order_by(TargetRow.target_id)
            )
            result = db.execute(q).fetchall()
            for target in result:
                canonical_address = get_canonical_address(target.address)
                if canonical_address:
                    q = (
                        TargetsTable.update(
                            values=dict(
                                ca=canonical_address,
                                cah=md5(target.owner_id + canonical_address),
                            )
                        )
                    ).where(TargetRow.target_id == target.target_id)
                    db.execute(q)
                else:
                    _logger.warning(
                        "bad canonical address for target %s", target.target_id
                    )

            if len(result) < limit:
                break
            cursor += limit
